<?php

namespace App\Backend\Http\Controllers;

use GuzzleHttp\Client;
use QL\QueryList;
use Chumper\Zipper\Zipper;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Storage;

class ZipController extends Controller
{
    public function pclzip()
    {
        $url = request('url');
        $zipper = new Zipper();
        if(isset($url)){
            $images = QueryList::get($url)
                ->rules([
                    'image'=>array('img','data-original'),
                ])->queryData();
            $time = $this->save($images,'true');
        }else{
            $images = request('images');
            $time = $this->save($images);
        }
        $resfile = 'article/'.@date("Ymd", time()).'/'.md5(time()).'.zip';
        $zipper->make( public_path('/storage/').$resfile)->add(public_path('/storage/article/').$time)->add(public_path('/jishe.com.url'))->close();
        Storage::deleteDirectory('/public/article/'.$time);
        return response()->json(['status'=>1,'resfile'=>$resfile]);
    }

    public function save($images,$url = 'false')
    {
        $client = new Client(['verify' => false]);  //忽略SSL错误
        $time =  time();
        Storage::makeDirectory('/public/article/'.$time);
        $saveDir =  public_path('/storage/article/').$time;
        foreach ($images as $img){
            if($url == 'true'){
                if($img['image']){
                    $path =  $saveDir.'/'. md5($img['image']) . '.jpg';
                    $client->get($img['image'], ['save_to' => $path]);  //保存远程url到文件
                }
            }else{
                if($img){
                    $path =  $saveDir.'/'. md5($img) . '.jpg';
                    $client->get($img, ['save_to' => $path]);  //保存远程url到文件
                }
            }
        }
        return $time;
    }
}
